package com.zenithmind.gateway.config;

import com.zenithmind.gateway.security.SecurityProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 默认配置管理器实现
 * 专门负责统一管理各种配置信息
 * 遵循单一职责原则：只负责配置的统一管理和访问
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DefaultConfigurationManager implements ConfigurationManager {
    
    private final GatewayRouteProperties gatewayRouteProperties;
    private final SecurityProperties securityProperties;
    private final DefaultRouteConfigProvider defaultRouteConfigProvider;

    @Override
    public Map<String, List<String>> getServiceRoutes() {
        return defaultRouteConfigProvider.mergeWithDefaults(gatewayRouteProperties.getServiceRoutes());
    }

    @Override
    public AuthConfiguration getAuthConfiguration() {
        return new DefaultAuthConfiguration(gatewayRouteProperties.getAuth());
    }

    @Override
    public SecurityConfiguration getSecurityConfiguration() {
        return new DefaultSecurityConfiguration(securityProperties);
    }

    @Override
    public void refreshConfiguration() {
        log.info("刷新网关配置");
        // 这里可以添加配置刷新逻辑，比如重新加载配置文件等
    }
    
    /**
     * 默认认证配置实现
     */
    private static class DefaultAuthConfiguration implements AuthConfiguration {
        private final GatewayRouteProperties.AuthConfig authConfig;
        
        public DefaultAuthConfiguration(GatewayRouteProperties.AuthConfig authConfig) {
            this.authConfig = authConfig;
        }
        
        @Override
        public boolean isEnabled() {
            return authConfig.isEnabled();
        }
    }
    
    /**
     * 默认安全配置实现
     */
    private static class DefaultSecurityConfiguration implements SecurityConfiguration {
        private final SecurityProperties securityProperties;
        
        public DefaultSecurityConfiguration(SecurityProperties securityProperties) {
            this.securityProperties = securityProperties;
        }
        
        @Override
        public boolean isEnabled() {
            return securityProperties.isEnabled();
        }
        
        @Override
        public List<String> getPublicPaths() {
            return securityProperties.getPublicPaths();
        }
        
        @Override
        public List<String> getProtectedPaths() {
            return securityProperties.getProtectedPaths();
        }
        
        @Override
        public List<String> getIgnoreUrls() {
            String ignoreUrls = securityProperties.getIgnoreUrls();
            if (ignoreUrls != null && !ignoreUrls.isEmpty()) {
                return List.of(ignoreUrls.split(","));
            }
            return List.of();
        }
    }
}
